const axios = require('axios');

// 测试API端点
const API_BASE_URL = 'http://localhost:3000/api/users';

// 测试手机号登录/注册
async function testWeChatPhoneLogin() {
  try {
    // 测试数据
    const testData = {
      phone_number: '13800138001',
      openid: 'test_openid_12345',
      unionid: 'test_unionid_12345'
    };
    
    console.log('Testing WeChat phone login/registration...');
    
    // 第一次调用 - 应该创建新用户
    console.log('\n1. Testing user creation with phone number...');
    const response1 = await axios.post(`${API_BASE_URL}/wechat-phone-login`, testData);
    console.log('Response:', response1.data);
    
    const { token, user } = response1.data;
    
    // 验证响应数据
    if (!token || !user) {
      throw new Error('Missing token or user in response');
    }
    
    console.log(`User created with ID: ${user.id}`);
    
    // 第二次调用 - 应该返回现有用户
    console.log('\n2. Testing existing user login...');
    const response2 = await axios.post(`${API_BASE_URL}/wechat-phone-login`, {
      phone_number: testData.phone_number
    });
    
    console.log('Response:', response2.data);
    
    // 验证返回的是同一个用户
    if (response2.data.user.id !== user.id) {
      throw new Error('User ID mismatch');
    }
    
    console.log('\n3. Testing user update with new openid/unionid...');
    const response3 = await axios.post(`${API_BASE_URL}/wechat-phone-login`, {
      phone_number: testData.phone_number,
      openid: 'updated_openid_67890',
      unionid: 'updated_unionid_67890'
    });
    
    console.log('Response:', response3.data);
    
    // 验证openid和unionid已更新
    if (response3.data.user.openid !== 'updated_openid_67890' || 
        response3.data.user.unionid !== 'updated_unionid_67890') {
      throw new Error('User openid/unionid not updated');
    }
    
    console.log('\nAll tests passed!');
    
  } catch (error) {
    console.error('Test failed:', error.response ? error.response.data : error.message);
  }
}

testWeChatPhoneLogin();
